<?php

  function rateTag($url, $url_param, $tag, $up) {
    $return_string = "";

    if (!isset($_SESSION['user_name'])) {
      $return_string .= "<returncode>0</returncode>\n";
      $return_string .= "<errormessage>You're not logged in!</errormessage>\n";
      return $return_string;
    }
   
    $query = "SELECT id FROM WebPage WHERE url = '" . $url . "'";
    $result = mysql_query($query);
    if (mysql_num_rows($result) == 0) {
      $return_string .= "<returncode>0</returncode>\n";
      $return_string .= "<errormessage>No such tag</errormessage>\n";
      return $return_string;
    }
    $result_row = mysql_fetch_assoc($result);
    $webpage_id = $result_row['id'];
    $webpagequery_id = getPageParameterId($webpage_id, $url_param);
    $user_id = $_SESSION['user_id'];
    $query = "SELECT * FROM Tag WHERE text='$tag'";
    $result = mysql_query($query);
      
    if (mysql_num_rows($result) == 0) {
      $return_string .= "<returncode>0</returncode>\n";
      $return_string .= "<errormessage>No such tag</errormessage>\n";
      return $return_string;
    }
    $result_row = mysql_fetch_assoc($result);
    $tag_id = $result_row['id'];

    $query = "SELECT * FROM WebPageTagRating "
           . "WHERE webpagequery_id=$webpagequery_id "
           . "AND rater_user_id=$user_id AND tag_id=$tag_id"; 
    $result = mysql_query($query);

    $rating = $up == 'true' ? 1 : -1;

    if (mysql_num_rows($result) == 0) {
      $query = "INSERT INTO WebPageTagRating (webpagequery_id, "
             . "rater_user_id, tag_id, rating) "
             . "VALUES($webpagequery_id, $user_id, $tag_id, $rating)";
      $result = mysql_query($query);
    } else {
      $query = "UPDATE WebPageTagRating "
             . "SET rating=$rating "
             . "WHERE webpagequery_id=$webpagequery_id "
             . "AND rater_user_id=$user_id AND tag_id=$tag_id";
      $result = mysql_query($query);
    }
    $return_string .= "<returncode>1</returncode>";
    return $return_string;
  }
?>
